"""
@Author: CheyenneLam
@Date: 2020-12-16 10:31:00
@LastEditTime: 2020-12-16 10:31:00
@LastEditors: CheyenneLam
@Description: 钉钉通知
@FilePath: \Main\dding_notification.py
"""

import time
import hmac
import json
import hashlib
import base64
import requests
import urllib.parse
from sql import *

class DingTalk(object):
    """
        钉钉通知模块
    """

    def __init__(self, ding_env):
        self.ding_env = ding_env
        self.timestamp = str(round(time.time() * 1000))
        self.webhook = get_config(self.ding_env)["webhook_uri"]
        self.secret = get_config(self.ding_env)["secret"]

        secret_enc = self.secret.encode("utf-8")
        string_to_sign = "{}\n{}".format(self.timestamp, self.secret)
        string_to_sign_enc = string_to_sign.encode("utf-8")
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        self.sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))

    def sendMessage(self, content):
        headers = {
            "Content-Type": "application/json"
        }
        params = {}
        params["access_token"] = get_config(self.ding_env)["access_token"]
        params["timestamp"] = self.timestamp
        params["sign"] = self.sign
        try:
            resp = requests.post(self.webhook, headers=headers, params=params, data=json.dumps(content))
        except Exception as e:
            print("Send Failed, ERROR:{0}".format(e))
            return False
        else:
            if resp.status_code == 200:
                print("Send Success")
                return True
            else:
                print("Send Failed, StatusCode:{0}".format(resp.status_code))
                return False


if __name__ == '__main__':
    dingTalk = DingTalk()

    resp_data = {}
    resp_data['msgtype'] = "text"
    resp_data["text"] = {}
    resp_data["text"]["content"] = "巡检消息测试"

    dingTalk.sendMessage(resp_data)
